iT邦幫忙

0

Day 1: 20. Valid Parentheses

  • 分享至 

  • xImage
  •  

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
Example 5:
Input: s = "([)]"
Output: false
解題思路
這題的目標是判斷字串中的括號是否成對出現,且順序正確。也就是說,每一個開括號 (、[、{ 都必須有相對應的關括號 )、]、},並且遵守後進先出的原則。
1.建立一個堆疊(Stack):
用來暫存尚未被匹配的括號。
2.遍歷字串中的每個字元:
如果遇到左括號 (、[、{,
就把對應的右括號 )、]、} 推入堆疊中。
這樣做的好處是,當之後遇到右括號時,可以直接比對是否相同。
如果遇到右括號,則進行檢查:
若堆疊為空,代表沒有對應的左括號→不合法。
若堆疊頂端的符號不等於當前右括號→不匹配。
否則就把堆疊頂端元素彈出,繼續往下比對。
3.遍歷結束後檢查堆疊:
如果堆疊是空的 → 所有括號都正確匹配,回傳 true。
如果堆疊還有剩 → 表示有未關閉的括號,回傳 false。
https://ithelp.ithome.com.tw/upload/images/20251011/201794245cvN6ECG8g.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言